package bean.managed;

import entity.RefundRequestEntity;
import bean.managed.util.JsfUtil;
import bean.session.RefundEntityFacade;
import bean.session.RefundRequestEntityFacade;

import bean.session.SalesOrderEntityFacade;
import entity.RefundEntity;
import entity.SalesOrderEntity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import type.InternalStatus;
import type.RefundRequestStatus;

@ManagedBean(name = "refundRequestEntityController")
@SessionScoped
public class RefundRequestEntityController extends AbstractBacking implements Serializable {

    private RefundRequestEntity current;
    private List<RefundRequestEntity> allRefundRequests;
    private List<RefundRequestEntity> unprocessedRefundRequests;
    @EJB
    private bean.session.RefundRequestEntityFacade ejbFacade;
    @EJB
    private RefundEntityFacade refundFacade;
    @EJB
    private SalesOrderEntityFacade salesOrderFacade;

    public RefundRequestEntityController() {
    }

    public RefundRequestEntity getSelected() {
        if (current == null) {
            current = new RefundRequestEntity();
        }
        return current;
    }

    private RefundRequestEntityFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        return "View";
    }

    public String prepareCreate() {
        current = new RefundRequestEntity();
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RefundRequestEntityCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        return "Edit";
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RefundRequestEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        return "List";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RefundRequestEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void recreateModel() {
        current = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = RefundRequestEntity.class)
    public static class RefundRequestEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            RefundRequestEntityController controller = (RefundRequestEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "refundRequestEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof RefundRequestEntity) {
                RefundRequestEntity o = (RefundRequestEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + RefundRequestEntityController.class.getName());
            }
        }
    }

    public List<RefundRequestEntity> getAllRefundRequests() {
        allRefundRequests = ejbFacade.findAll();
        return allRefundRequests;
    }

    public void setAllRefundRequests(List<RefundRequestEntity> allRefundRequests) {
        this.allRefundRequests = allRefundRequests;
    }

    public List<RefundRequestEntity> getUnprocessedRefundRequests() {
        unprocessedRefundRequests = ejbFacade.getUnprocessedRefundRequests();
        return unprocessedRefundRequests;
    }

    public void setUnprocessedRefundRequests(List<RefundRequestEntity> unprocessedRefundRequests) {
        this.unprocessedRefundRequests = unprocessedRefundRequests;
    }

    public RefundRequestEntity getCurrent() {
        return current;
    }

    public void setCurrent(RefundRequestEntity current) {
        System.out.println("RefundRequest setting current: " + current);
        this.current = current;
    }

    private RefundEntity prepareRefund() {
        RefundEntity refund = new RefundEntity();
        refund.setCustomerAccount(current.getSalesOrder().getCustomer().getCustomerAccount());
        refund.setRefundRequest(current);
        refund.created(getLoginPerson());
        refundFacade.create(refund);

        return refund;
    }

    public void prepareRefundApprove() {
        System.out.println("prepare refund approve");
        RefundEntity refund = prepareRefund();

        current.setStatus(RefundRequestStatus.approved);
        current.setRefund(refund);

        SalesOrderEntity so = current.getSalesOrder();
        so.modified(getLoginPerson());
        so.setInternalStatus(InternalStatus.RefundConfirmPending);
    }

    public void prepareRefundReject() {
        System.out.println("prepare refund reject");
        RefundEntity refund = prepareRefund();

        current.setStatus(RefundRequestStatus.rejected);
        current.setRefund(refund);

        SalesOrderEntity so = current.getSalesOrder();
        so.modified(getLoginPerson());
        so.setInternalStatus(InternalStatus.RefundrequestRejected);
    }

    public String recordRefundDecision() {
        update();
        salesOrderFacade.edit(current.getSalesOrder());
        
        return "/entities/refundRequestEntity/List.xhtml";
    }

    public void recordRefund() {
        RefundEntity refund = current.getRefund();
        refund.setRefundDate(new Date());
        refund.modified(getLoginPerson());
        refundFacade.edit(refund);

        current.setStatus(RefundRequestStatus.fulfilled);
        update();

        SalesOrderEntity so = current.getSalesOrder();
        so.setInternalStatus(InternalStatus.RefundComplete);
        so.modified(getLoginPerson());
        salesOrderFacade.edit(current.getSalesOrder());
    }
}
